import multiprocessing
import threading

import webview
from PIL import Image
from pystray import Icon, Menu, MenuItem

from config import app_data

Process = multiprocessing.Process
Queue = multiprocessing.Queue
webview_process = None


def run_webview():
    chinese = {
        'global.quitConfirmation': "确认退出"
    }

    app_data.main_window = webview.create_window('Webview', 'https://baidu.com',
                                                 confirm_close=True, localization=chinese)
    app_data.main_window.events.closing += on_closing
    # 禁止在新的浏览器窗口中打开
    webview.settings["OPEN_EXTERNAL_LINKS_IN_BROWSER"] = False
    # 设置远程调试端口
    webview.settings['REMOTE_DEBUGGING_PORT'] = '59222'
    webview.start(icon='assets/logo.ico')


def start_webview_process():
    global webview_process
    # 注意，使用了进程后变量的数据不共享
    webview_process = Process(target=run_webview)
    webview_process.start()


def on_app_open(icon_tray, item):
    app_data.main_window.show()
    if not webview_process.is_alive():
        start_webview_process()


def on_app_exit(icon_tray, item):
    print("on_app_exit")
    icon_tray.stop()


def on_closing(window):
    print('pywebview 窗口正在关闭')
    window.create_confirmation_dialog('提示', '应用已隐藏到托盘，你可以从托盘再次打开')
    window.hide()
    return False


def start_icon_tray():
    open_item = MenuItem('打开', on_app_open)
    exit_item = MenuItem('退出', on_app_exit)
    menu = Menu(open_item, exit_item)
    image = Image.open('../assets/logo.ico')
    icon_tray = Icon('Pystray', image, menu=menu)
    icon_tray.run()


if __name__ == '__main__':
    start_webview_process()
    # start_icon_tray()
    webview_process.terminate()
